<?php

/**
 * Created by PhpStorm.
 * User: bill-h
 * Date: 2021/10/11
 * Time: 15:20
 * Email: 391878487@qq.com
 */
namespace app\api\controller\v1;

use app\Request;
use app\services\BaseServices;
use utils\JwtAuth;
use services\CacheService;
use think\facade\Config;
use app\api\model\User;


class LoginController extends BaseServices
{
    /**
     * 账号密码登录
     *
     */
    public function login($account, $password)
    {
        $this->model=new User();

        $user = $this->model->getOne(['account|phone' => $account]);
        if ($user) {
            if ($user->pwd !== md5((string)$password))
                return  app('json')->fail('账号或密码错误');
            if ($user->pwd === md5('123456'))
                return   app('json')->fail('请修改您的初始密码，再尝试登录！');

        } else {
            return  app('json')->fail('账号或密码错误');
        }
        if (!$user['status'])
            return  app('json')->fail('已被禁止，请联系管理员');
        try{
            $token = $this->createToken((int)$user['uid'], 'api');
        }catch (\Throwable $e){
            return  app('json')->fail($e->getMessage());
        }

        if ($token) {
            return app('json')->success('登录成功',['token' => $token['token'], 'expires_time' => $token['params']['exp']]);
        } else
            return  app('json')->fail('登录失败');


    }

    /**
     * 登录后操作
     *
     */
    public function authlogin(Request $request)
    {

        $user = $request->uid();
        return app('json')->success('授权成功', [$user]);
    }

    /**
     * 退出
     * @param Request $request
     */
    public function logout(Request $request){
        $key = trim(ltrim($request->header(Config::get('cookie.token_name')), 'Bearer'));
        CacheService::redisHandler()->delete($key);
        return app('json')->success('成功');
    }

    /**
     * 创建token
     * @param int $id
     * @param $type
     * @return array
     */
    public function createToken(int $id, $type)
    {
        /** @var JwtAuth $jwtAuth */
        $jwtAuth = app()->make(JwtAuth::class);

        return $jwtAuth->createToken($id, $type);
    }

}